package com.woniuxy.userassembly.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ygj
 */
@Configuration
@Component
public class RabbitConfig {

    public static final String EXCHANGE_NAME="EXCHANGE_SPRING_BOOT_02";
    public static final String QUEUE_NAME="QUEUE_SPRING_BOOT_02";
    public static final String ROUTING_NAME="ROUTING_SPRING_BOOT_02";
    public static final String DL_EXCHANGE_NAME="EXCHANGE_SPRING_BOOT_DL";
    public static final String DL_QUEUE_NAME="QUEUE_SPRING_BOOT_DL";
    public static final String DL_ROUTING_NAME="ROUTING_SPRING_BOOT_DL";

    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange(EXCHANGE_NAME);
    }

    @Bean
    public Queue queue(){
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange",DL_EXCHANGE_NAME);
        arguments.put("x-dead-letter-routing-key",DL_ROUTING_NAME);
        Queue queue = new Queue(QUEUE_NAME,false,false,false,arguments);
        return queue;
    }

    @Bean
    public Binding binding(){
        return BindingBuilder.bind(queue()).to(topicExchange()).with(ROUTING_NAME);
    }


    @Bean
    public TopicExchange  topicExchange2(){
        return new TopicExchange(DL_EXCHANGE_NAME);
    }

    @Bean
    public Queue queue2(){
        return new Queue(DL_QUEUE_NAME);
    }

    @Bean
    public Binding binding2(){
        return BindingBuilder.bind(queue2()).to(topicExchange2()).with(DL_ROUTING_NAME);
    }

    @Bean
    public RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate();
        configurer.configure(template, connectionFactory);
        //使用json序列化对象
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        return template;
    }

}

